﻿
Imports Aspose.Words
Imports System.Net
Imports System.IO
Imports System.IO.Path
Imports System.Data
Imports VSModel
Imports Cls_Common
Imports clsDALabelPrint
Imports SecurityService
Partial Class Control_PrintLabel_Create3P
    Inherits System.Web.UI.UserControl

    Protected Sub btnSave_Click(sender As Object, e As System.EventArgs) Handles btnSave.Click
        If txtItemCode.Text.Trim = "" Or hidVendorCode.Text = "" Then
            Excute_Javascript("AlertboxRedirect('Vui lòng nhập itemcode và vendor code.','../../Page/PrintLabel/Create3P.aspx');", Me.Page, True)
            Exit Sub
        End If
        Using data As New VSEntities
            'create WareHouse
            Call Save()

            Dim p = (From q In data.WareHouses Where q.BatchNo = hidBatchNo.Value Select q).FirstOrDefault

            If p Is Nothing Then
                Excute_Javascript("Alertbox('Không tồn tại dữ liệu có Batch No này, Vui lòng kiểm tra lại.');", Me.Page, True)
            Else
                'Excute_Javascript("Alertbox('Có data ');", Me.Page, True)
                Try
                    Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
                    If Not applicationPath.EndsWith("\") Then
                        applicationPath = applicationPath + "\"
                    End If
                    Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Words.lic")
                    If (File.Exists(licenseFile)) Then
                        Dim license As Aspose.Words.License = New Aspose.Words.License()
                        license.SetLicense(licenseFile)

                        Dim strDocFile As String = getDocFile()
                        Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)

                        Dim strDirTemp As String = applicationPath & "viewerTemp"
                        If Not Directory.Exists(strDirTemp) Then
                            Directory.CreateDirectory(strDirTemp)
                        End If
                        If Not strDirTemp.EndsWith("\") Then
                            strDirTemp = strDirTemp + "\"
                        End If

                        Dim swfFile As String = GetFileNameWithoutExtension(strDocFile) & ".swf"
                        Dim pngTemp As String = strDirTemp & swfFile
                        doc.Save(pngTemp, Aspose.Words.SaveFormat.Swf)

                        If File.Exists(pngTemp) Then
                            Call writeSwf("../../viewerTemp/" & swfFile)
                        End If
                        If Not IsNothing(doc) Then
                            doc = Nothing
                        End If
                    End If
                Catch ex As Exception

                End Try
            End If

        End Using
    End Sub

    Function getDocFile() As String
        Dim strResult As String = ""
        Try
            Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
            If Not applicationPath.EndsWith("\") Then
                applicationPath = applicationPath + "\"
            End If
            Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Words.lic")
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)

                Dim strDocFile As String = applicationPath & "Template\labelTemplate.doc"
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)

                Dim builder As DocumentBuilder = New DocumentBuilder(doc)
                Using data As New VSEntities
                    'lay hinh do canh bao
                    Dim iLst As IList = (From q In data.uspLabelGetHinhDo(hidBatchNo.Value, 1) Select q).ToList

                    Dim _iLstCanhBao As IList = (From q In data.uspLabelGetHinhDo(hidBatchNo.Value, -1) Select q Order By q.CanhBaoNguyCo).ToList

                    Dim intSeq As Integer = 1
                    Dim FileURL As String = ""
                    Dim strTuCanhBao As String = ""
                    Dim _CanhBaoNguyCo As String = ""
                    Dim fieldName1 As String = "iconWarning1"
                    Dim fieldName2 As String = "iconWarning2"
                    Dim fieldName3 As String = "iconWarning3"
                    Dim fieldName4 As String = "iconWarning4"
                    Dim fieldName5 As String = "iconWarning5"
                    Dim arrFileURL As String = "" 'dung de luu ca'c file URL va bo trung lap

                    If Not _iLstCanhBao Is Nothing AndAlso iLst.Count > 0 Then
                        Dim strTemp As String = ""
                        Dim strCanhBao As String = ""
                        For Each proc In _iLstCanhBao
                            _CanhBaoNguyCo = proc.CanhBaoNguyCo.ToString
                            If _CanhBaoNguyCo <> strTemp Then
                                strCanhBao = strCanhBao & " " & RemoveHtmlTags(_CanhBaoNguyCo)
                            End If
                            strTemp = _CanhBaoNguyCo
                        Next
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo1", strCanhBao)
                    End If

                    If Not iLst Is Nothing AndAlso iLst.Count > 0 Then
                        For Each proc In iLst
                            FileURL = ""
                            If Not IsNothing(proc.FileURL) Then
                                'hinh do normal hay NoneEdge
                                If ddlLabelType.SelectedValue = 0 Then
                                    FileURL = proc.FileURL.ToString
                                Else
                                    FileURL = proc.FileURLNone.ToString
                                End If

                                _CanhBaoNguyCo = proc.CanhBaoNguyCo.ToString
                                strTuCanhBao = strTuCanhBao & "@" & proc.TuCanhBao.ToString
                                arrFileURL = arrFileURL + "@" + FileURL
                            End If
                            'Select Case intSeq
                            '    Case 1
                            '        ' InsertImageFromURL(builder, FileURL, 85, 85, fieldName1)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo1", _CanhBaoNguyCo.Trim)
                            '    Case 2
                            '        'InsertImageFromURL(builder, FileURL, 85, 85, fieldName2)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo2", _CanhBaoNguyCo.Trim)
                            '    Case 3
                            '        ' InsertImageFromURL(builder, FileURL, 85, 85, fieldName3)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo3", _CanhBaoNguyCo.Trim)
                            '    Case 4
                            '        ' InsertImageFromURL(builder, FileURL, 85, 85, fieldName4)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo4", _CanhBaoNguyCo.Trim)
                            '    Case 5
                            '        ' InsertImageFromURL(builder, FileURL, 85, 85, fieldName5)
                            '        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo5", _CanhBaoNguyCo.Trim)
                            'End Select
                            'intSeq += 1
                        Next

                        ' xu ly file Hinh do bi dublicate
                        Dim arrFileURLResult = removeDublicate(arrFileURL)
                        intSeq = 1
                        For Each _fileURL In arrFileURLResult
                            Select Case intSeq
                                Case 1
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName1)
                                Case 2
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName2)
                                Case 3
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName3)
                                Case 4
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName4)
                                Case 5
                                    InsertImageFromURL(builder, _fileURL, 85, 85, fieldName5)
                            End Select
                            intSeq = intSeq + 1
                        Next
                        'end xu ly file hinh do bi dublicate

                        FileURL = "http://" & HttpContext.Current.Request.ServerVariables("HTTP_HOST") & ConfigurationManager.AppSettings("ApplicationName") & "/Images/warnBlank.png"
                        For i As Integer = arrFileURLResult.Length + 1 To 5
                            Select Case i
                                Case 1
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName1)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo1", "")
                                Case 2
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName2)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo2", "")
                                Case 3
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName3)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo3", "")
                                Case 4
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName4)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo4", "")
                                Case 5
                                    InsertImageFromURL(builder, FileURL, 85, 85, fieldName5)
                                    InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo5", "")
                            End Select
                        Next
                    Else
                        FileURL = "http://" & HttpContext.Current.Request.ServerVariables("HTTP_HOST") & ConfigurationManager.AppSettings("ApplicationName") & "/Images/warnBlank.png"
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName1)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo1", "Không có")
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName2)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo2", "")
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName3)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo3", "")
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName4)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo4", "")
                        InsertImageFromURL(builder, FileURL, 85, 85, fieldName5)
                        InsertCanhBaoNguyCo(builder, "CanhBaoNguyCo5", "")
                    End If

                    'add tu canh bao
                    builder.MoveToMergeField("TuCanhBao")
                    builder.Bold = True
                    builder.Font.Name = "Arial"
                    builder.Font.Size = "8"
                    strTuCanhBao = strTuCanhBao.ToUpper
                    strTuCanhBao = getWarning(strTuCanhBao)
                    builder.Write(strTuCanhBao)
                End Using

                'xu ly thanh phan supscript


                Dim clstp As New clsDALabelPrint
                Dim dttp As DataTable = clstp.SelectLabelPrint(hidBatchNo.Value)
                clstp.Destructor()
                clstp = Nothing

                InsertThanhPhan(builder, hidBatchNo.Value)

                'If dttp.Rows.Count > 0 Then
                '    InsertThanhPhan(builder, "ThanhPhan_1", dttp.Rows(0)("ThanhPhan_1"))
                '    InsertThanhPhan(builder, "ThanhPhan_2", dttp.Rows(0)("ThanhPhan_2"))
                '    InsertThanhPhan(builder, "ThanhPhan_3", dttp.Rows(0)("ThanhPhan_3"))
                '    InsertThanhPhan(builder, "ThanhPhan_4", dttp.Rows(0)("ThanhPhan_4"))
                '    InsertThanhPhan(builder, "ThanhPhan_5", dttp.Rows(0)("ThanhPhan_5"))
                'Else
                '    InsertThanhPhan(builder, "ThanhPhan_1", "")
                '    InsertThanhPhan(builder, "ThanhPhan_2", "")
                '    InsertThanhPhan(builder, "ThanhPhan_3", "")
                '    InsertThanhPhan(builder, "ThanhPhan_4", "")
                '    InsertThanhPhan(builder, "ThanhPhan_5", "")
                'End If


                Dim cls As New clsDALabelPrint
                Dim dt As DataTable = cls.SelectLabelPrint(hidBatchNo.Value)
                cls.Destructor()
                cls = Nothing
                If dt.Rows.Count > 0 Then
                    If dt.Rows(0)("TradeName").ToString.Length > 40 Then
                        builder.MoveToMergeField("TradeName")
                        builder.InsertHtml("<span style='font-size:10pt; font-family:Arial'>" & dt.Rows(0)("TradeName").ToString.Trim & "</span>")
                    End If

                    If dt.Rows(0)("UNNo").ToString <> "" Then
                        builder.MoveToMergeField("UN")
                        builder.Font.Size = "14"
                        builder.Write("UN" & dt.Rows(0)("UNNo").ToString)
                    Else
                        builder.MoveToMergeField("UN")
                        builder.Write("")
                    End If

                    doc.MailMerge.Execute(dt)
                    strResult = applicationPath & "viewerTemp"
                    If Not Directory.Exists(strResult) Then
                        Directory.CreateDirectory(strResult)
                    End If
                    If Not strResult.EndsWith("\") Then
                        strResult = strResult + "\"
                    End If
                    strResult &= Format(Now, "yyyyMMddhhmmssfff") & ".doc"
                    doc.Save(strResult, Aspose.Words.SaveFormat.Doc)
                    If Not IsNothing(doc) Then
                        'log here
                        Insert_App_Log("Print Label Item: " & txtItemCode.Text.Trim & ", Vendor: " & hidVendorCode.Text, Function_Name.PrintLabel, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                        doc = Nothing
                    End If
                End If
            End If
        Catch ex As Exception
            Excute_Javascript("Alertbox('Xuất hiện lỗi:" & ex.Message.ToString & "');", Me.Page, True)
        End Try
        Return strResult
    End Function
    Function getWarning(ByVal str As String) As String
        Dim lstArr = str.Split("@")
        If lstArr.Contains("NGUY HIỂM") Then
            Return "NGUY HIỂM"
        ElseIf lstArr.Contains("CẢNH BÁO") Then
            Return "CẢNH BÁO"
        Else
            Return "KHÔNG CÓ"
        End If

    End Function
    'remove dublicate item in Array
    Function removeDublicate(ByVal arr As String) As String()
        Dim lstArr = arr.Split("@")
        Dim lstResult() As String = {}
        Dim i = 0
        For Each a In lstArr
            'neu mang da add ko chua phan tu cua a
            If Not lstResult.Contains(a) AndAlso a <> "" Then
                ReDim Preserve lstResult(i)
                lstResult(i) = a
                i = i + 1
            End If
        Next
        Return lstResult
    End Function

    Private Sub writeSwf(ByVal _swf As String)
        Try
            Dim _xmlFile As String = ""
            Dim _strInfo As String = ""
            If _swf.ToLower.EndsWith(".swf") Then
                _strInfo &= " writeSwf('" & _swf & "');" & vbCrLf
            End If
            Excute_Javascript(_strInfo, Me.Page, True)
        Catch ex As Exception
        End Try
    End Sub
#Region "XulyDatatable"
    'Fill data from linq to Datatable
    Private Function FillDataTable(ByRef iDataTable As DataTable) As Boolean
        Dim bolResult As Boolean = False
        Try


            If Not iDataTable Is Nothing AndAlso iDataTable.Rows.Count = 0 Then
                Dim arrColumns(24) As String
                Dim arrRows(24) As String
                arrColumns(0) = "TradeName"
                arrColumns(1) = "CASNo"
                arrColumns(2) = "ECNo"
                arrColumns(3) = "UNNo"
                arrColumns(4) = "ItemCode"
                arrColumns(5) = "ManufactureName"
                arrColumns(6) = "ManuAddress"
                arrColumns(7) = "ManuDienThoai"
                arrColumns(8) = "ManuFax"
                arrColumns(9) = "ProName"
                arrColumns(10) = "ProAddress"
                arrColumns(11) = "ProDienThoai"
                arrColumns(12) = "ProFax"
                arrColumns(13) = "Original"
                arrColumns(14) = "Netweight"
                arrColumns(15) = "DonVi"
                arrColumns(16) = "DVT"
                arrColumns(17) = "NgaySanXuat"
                arrColumns(18) = "HanSuDung"
                arrColumns(19) = "ThanhPhan_1"
                arrColumns(20) = "ThanhPhan_2"
                arrColumns(21) = "ThanhPhan_3"
                arrColumns(22) = "ThanhPhan_4"
                arrColumns(23) = "VendorCode"
                arrColumns(24) = "MaSanPham"

                Using data As New VSEntities
                    Dim iLst As IList = (From q In data.uspLabelPrintByBatchNo(hidBatchNo.Value) Select q).ToList
                    If Not iLst Is Nothing AndAlso iLst.Count > 0 Then
                        Dim _sequence As Integer = 1
                        For Each proc In iLst
                            With proc
                                arrRows(0) = .TradeName.ToString
                                arrRows(1) = .CASNo.ToString
                                arrRows(2) = .ECNo.ToString
                                arrRows(3) = .UNNo.ToString
                                arrRows(4) = .ItemCode.ToString
                                arrRows(5) = .ManufactureName.ToString
                                arrRows(6) = .ManuAddress.ToString
                                arrRows(7) = .ManuDienThoai.ToString
                                arrRows(8) = .ManuFax.ToString
                                arrRows(9) = .ProName.ToString
                                arrRows(10) = .ProAddress.ToString
                                arrRows(11) = .ProDienThoai.ToString
                                arrRows(12) = .ProFax.ToString
                                arrRows(13) = .Original.ToString
                                arrRows(14) = .Netweight.ToString
                                arrRows(15) = .DonVi.ToString
                                arrRows(16) = .DVT.ToString
                                arrRows(17) = .NgaySanXuat
                                arrRows(18) = .HanSuDung
                                arrRows(19) = .ThanhPhan_1.ToString
                                arrRows(20) = .ThanhPhan_2.ToString
                                arrRows(21) = .ThanhPhan_3.ToString
                                arrRows(22) = .ThanhPhan_4.ToString
                                arrRows(23) = .VendorCode.ToString
                                arrRows(24) = .MaSanPham.ToString
                            End With
                            AddRowDataTable(iDataTable, arrColumns, arrRows)
                        Next
                        bolResult = True
                    End If
                End Using
            End If
        Catch ex As Exception : End Try
        Return bolResult
    End Function

    'Create a datatable to save all input fields
    Private Function GetDataTable() As DataTable
        Try
            Dim _tempTable As New DataTable
            Dim arrColumns(24) As String
            Dim arrType(24) As String
            arrColumns(0) = "TradeName"
            arrColumns(1) = "CASNo"
            arrColumns(2) = "ECNo"
            arrColumns(3) = "UNNo"
            arrColumns(4) = "ItemCode"
            arrColumns(5) = "ManufactureName"
            arrColumns(6) = "ManuAddress"
            arrColumns(7) = "ManuDienThoai"
            arrColumns(8) = "ManuFax"
            arrColumns(9) = "ProName"
            arrColumns(10) = "ProAddress"
            arrColumns(11) = "ProDienThoai"
            arrColumns(12) = "ProFax"
            arrColumns(13) = "Original"
            arrColumns(14) = "Netweight"
            arrColumns(15) = "DonVi"
            arrColumns(16) = "DVT"
            arrColumns(17) = "NgaySanXuat"
            arrColumns(18) = "HanSuDung"
            arrColumns(19) = "ThanhPhan_1"
            arrColumns(20) = "ThanhPhan_2"
            arrColumns(21) = "ThanhPhan_3"
            arrColumns(22) = "ThanhPhan_4"
            arrColumns(23) = "VendorCode"
            arrColumns(24) = "MaSanPham"

            arrType(0) = "System.String"
            arrType(1) = "System.String"
            arrType(2) = "System.String"
            arrType(3) = "System.String"
            arrType(4) = "System.String"
            arrType(5) = "System.String"
            arrType(6) = "System.String"
            arrType(7) = "System.String"
            arrType(8) = "System.String"
            arrType(9) = "System.String"
            arrType(10) = "System.String"
            arrType(11) = "System.String"
            arrType(12) = "System.String"
            arrType(13) = "System.String"
            arrType(14) = "System.String"
            arrType(15) = "System.String"
            arrType(16) = "System.String"
            arrType(17) = "System.String"
            arrType(18) = "System.String"
            arrType(19) = "System.String"
            arrType(20) = "System.String"
            arrType(21) = "System.String"
            arrType(22) = "System.String"
            arrType(23) = "System.String"
            arrType(24) = "System.String"

            _tempTable = MakeNameTable("viewerDT", arrColumns, arrType)
            Return _tempTable
        Catch ex As Exception
            Return Nothing
        End Try
    End Function


    Public Function MakeNameTable(ByVal TableName As String, ByVal arrColumn() As String, ByVal arrType() As String) As DataTable
        Try
            Dim namesTable As DataTable = New DataTable(TableName)
            Dim keys(0) As DataColumn
            For i As Integer = 0 To UBound(arrColumn)
                Dim idColumn As DataColumn = New DataColumn
                idColumn.DataType = Type.GetType(arrType(i))
                idColumn.ColumnName = arrColumn(i)
                namesTable.Columns.Add(idColumn)
                If i = 0 Then
                    keys(0) = idColumn
                End If
            Next
            namesTable.PrimaryKey = keys
            Return namesTable
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Public Sub AddRowDataTable(ByRef iDatatable As DataTable, ByVal arrColumn() As String, ByVal arrRow() As String, Optional ByVal insertIndex As Integer = 0)
        Try
            Dim iRowData As DataRow = iDatatable.NewRow()
            For i As Integer = 0 To UBound(arrColumn)
                iRowData(arrColumn(i)) = arrRow(i)
            Next
            If insertIndex > 0 Then
                iDatatable.Rows.InsertAt(iRowData, insertIndex)
            Else
                iDatatable.Rows.Add(iRowData)
            End If
        Catch ex As Exception : End Try
    End Sub
    Public Sub RemoveRowDataTable(ByRef iDatatable As DataTable, ByVal index As Integer)
        Dim iRowData As DataRow = iDatatable.Rows.Find(index)
        If Not iDatatable Is Nothing Then
            iDatatable.Rows.Remove(iRowData)
        End If
    End Sub

#End Region
    Private Sub InsertImageFromURL(ByVal builder As DocumentBuilder, ByVal url As String, ByVal width As Double, ByVal height As Double, ByVal fieldName As String)

        If ddlLabelType.SelectedValue = 1 AndAlso url.IndexOf("warnBlank.png") <> -1 Then
            builder.MoveToMergeField(fieldName)
            builder.Write("")
        Else
            Try
                'Prepare the web page we will be asking for
                Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
                request.Method = "GET"
                request.ContentType = "image/JPEG"
                request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0"
                'Execute the request
                Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
                'We will read data via the response stream
                Dim resStream As Stream = response.GetResponseStream()
                'Write content into the MemoryStream
                Dim resReader As New BinaryReader(resStream)
                Dim imgStream As New MemoryStream(resReader.ReadBytes(CInt(response.ContentLength)))
                'Insert image into the document
                builder.MoveToMergeField(fieldName)
                builder.InsertImage(imgStream, width, height)
                'Handle web exceptions
            Catch
            End Try

        End If
   

    End Sub



    Private Sub InsertCanhBaoNguyCo(ByVal builder As DocumentBuilder, ByVal fieldName As String, ByVal _str As String)
        'Insert text to file
        builder.MoveToMergeField(fieldName)
        builder.Font.Size = "8"
        builder.Write(RemoveHtmlTags(_str).Trim())

    End Sub

    Private Sub InsertThanhPhanHTML(ByVal builder As DocumentBuilder, ByVal fieldName As String, ByVal _str As String)
        'Insert html to file
        builder.MoveToMergeField(fieldName)
        builder.InsertHtml("<span style='font-size:7pt; font-family:Arial'>" & _str.Trim & "</span>")
    End Sub


    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        'xu ly jquery khi post back
        Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
        If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
            ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
        Else
            Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
        End If
    End Sub
    Protected Sub Save()
        Using data As New VSEntities
            Dim p As New VSModel.WareHouse

            p.BatchNo = "Auto" & Guid.NewGuid.ToString
            p.ItemCode = txtItemCode.Text.Trim()

            p.VendorCode = hidVendorCode.Text

            p.ManufacturedDate = StringToDate(txtNgaySanXuat.Text.Trim())
            p.ExpiredDate = StringToDate(txtHanSuDung.Text.Trim())
            p.PackingSize = txtPackageSize.Text.Trim()
            p.PackingType = txtPackageType.Text.Trim()
            p.BUN = txtBUN.Text.Trim()

            'p.Source = txtSource.Text.Trim()
            'p.Pallet = txtPallet.Text.Trim()

            'p.StockOnHand = txtStockOnhand.text()

            p.Creator = Session("Username")
            p.Created = Now()
            p.StatusId = 1 'drapt
            data.WareHouses.AddObject(p)
            data.SaveChanges()
            hidBatchNo.Value = p.BatchNo
            'Insert_App_Log("Insert  Warehouse:" & txtTitle.Text.Trim & "", Function_Name.Warehouse, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))


        End Using
    End Sub

    Protected Sub btnReset_Click(sender As Object, e As System.EventArgs) Handles btnReset.Click
        Response.Redirect(MainDomain & "Page/PrintLabel/Create3P.aspx")
    End Sub

    Protected Sub btnExportWord_Click(sender As Object, e As System.EventArgs) Handles btnExportWord.Click
        Save()
        Dim strFileName = getDocFile()
        Dim bareFile = strFileName.Replace(Server.MapPath("~/viewerTemp/"), "")
        Excute_Javascript("open_iframe('" + MainDomain & "Page/PrintLabel/ExportFile.aspx?f=" + bareFile + "','NhanHoaChat')", Me.Page)

    End Sub
    

    Protected Sub btnExportPdf_Click(sender As Object, e As System.EventArgs) Handles btnExportPdf.Click
        Save()
        Dim strDocFile = getDocFile()
        'save PDF
        Dim strPdfFile As String = strDocFile.Replace(".doc", ".pdf")
        If Not File.Exists(strPdfFile) Then
            Dim licenseFile As String = Server.MapPath("~") & "\bin\Aspose.Words.lic"
            If (File.Exists(licenseFile)) Then
                Dim license As Aspose.Words.License = New Aspose.Words.License()
                license.SetLicense(licenseFile)
                Dim doc As Aspose.Words.Document = New Aspose.Words.Document(strDocFile)
                doc.Save(strPdfFile, SaveFormat.Pdf)
                If Not IsNothing(doc) Then
                    doc = Nothing
                End If
            End If
        End If

        Dim bareFile = strPdfFile.Replace(Server.MapPath("~/viewerTemp/"), "")
        Excute_Javascript("open_iframe('" + MainDomain & "Page/PrintLabel/ExportFile.aspx?f=" + bareFile + "','NhanHoaChat')", Me.Page)

    End Sub

    Private Sub InsertThanhPhan(ByVal builder As DocumentBuilder, ByVal _BatchNo As String)
        Using data As New VSEntities
            Dim p = data.uspLabelGetThanhPhan(_BatchNo).ToList
            If Not p Is Nothing Then
                If p.Count > 4 Then
                    InsertThanhPhanHTML(builder, "ThanhPhan_1", "Hỗn hợp chất nhiều thành phần")
                Else
                    Dim i = 1
                    For Each a In p
                        InsertThanhPhanHTML(builder, "ThanhPhan_" & i.ToString, a.ThanhPhanNguyHiem & IIf(Not a.SoCAS Is Nothing AndAlso a.SoCAS <> "", " CAS " & a.SoCAS, "") & " " & a.CongThucHoaHoc & " " & a.HamLuong)
                        i = i + 1
                    Next
                End If
            End If
            'replace empty string in Label
            InsertThanhPhanHTML(builder, "ThanhPhan_1", "")
            InsertThanhPhanHTML(builder, "ThanhPhan_2", "")
            InsertThanhPhanHTML(builder, "ThanhPhan_3", "")
            InsertThanhPhanHTML(builder, "ThanhPhan_4", "")


        End Using
    End Sub
End Class



